package main.interaction
{
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	public class InteractiveRegion extends EventDispatcher
	{
		
		public var region:Region;
		public var label:String;
		public var regionName:String;
		public var targetState:String;
		
		private var _enabled:Boolean = false;
		
		public function InteractiveRegion()
		{
		}
		
		public function set enabled(b:Boolean):void {
			if (b) {
				region.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
				region.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
				region.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			} else {
				region.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
				region.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
				region.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			}
			_enabled = b;
			region.enabled = b;
		}
		
		public function get enabled():Boolean {
			return _enabled;
		}
		
		private function onMouseOver(e:MouseEvent):void {
			dispatch(StateEvent.REGION_OVER);
		}
		
		private function onMouseOut(e:MouseEvent=null):void {
			dispatch(StateEvent.REGION_OUT);
		}
		
		private function onMouseUp(e:MouseEvent):void {
			onMouseOut();
			dispatch(StateEvent.REGION_UP);
		}
		
		
		private function dispatch(type:String):void {
			var ev:StateEvent = new StateEvent(type);
			ev.interactiveRegion = this;
			dispatchEvent(ev);
		}
	
		public static function fromXML(xml:XML):InteractiveRegion {
			if (!xml) throw new Error("Trying to create InteractiveRegion from null xml");
			var r:InteractiveRegion = new InteractiveRegion();
			r.label = xml.@label;
			r.regionName = xml.@region;
			r.targetState = xml.@targetState;
			return r;
		}
	
	}
}